﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SlimDX;
using DarkLight.Model;

namespace DarkLight
{
    public static class MathHelper
    {
        public static Vector3 ToVector3(this Vector4 vector)
        {
            return new Vector3(vector.X, vector.Y, vector.Z);
        }

        public static Vector4 ToVector4(this Vector3 vector)
        {
            return ToVector4(vector, 0);
        }

        public static Vector4 ToVector4(this Vector3 vector, float wValue)
        {
            return new Vector4(vector, wValue);
        }

        public static Vector3 ToVector3(this Spherical coordinates)
        {
            if (object.ReferenceEquals(coordinates, null))
                return Vector3.Zero;

            double rho = coordinates.Rho;
            double cosTheta = Math.Cos(coordinates.Theta);
            double sinTheta = Math.Sin(coordinates.Theta);
            double cosPhi = Math.Cos(coordinates.Phi);
            double sinPhi = Math.Sin(coordinates.Phi);

            double X = rho * sinPhi* cosTheta;
            double Y = rho * sinPhi * sinTheta;
            double Z = rho * cosPhi;
            return new Vector3((float)X, (float)Y, (float)Z);
        }

        public static Spherical ToSphericalCS(this Vector3 coordinates)
        {
            double x = coordinates.X;
            double y = coordinates.Y;
            double z = coordinates.Z;

            double r = Math.Sqrt(x * x + y * y);
            double rho = Math.Sqrt(x * x + y * y + z * z);

            double phi = 0;
            if (z > 0) phi = Math.Atan2(r, z);
            else if (z < 0) phi = Math.Atan2(r, z);
            else if (z == 0) phi = Math.PI / 2;

            double theta = 0;
            if (x > 0 && y >= 0) theta = Math.Atan2(y, x);
            else if (x > 0 && y < 0) theta = Math.Atan2(y, x) + 2 * Math.PI;
            else if (x < 0) theta = Math.Atan2(y, x);
            else if (x == 0 && y > 0) theta = Math.PI / 2;
            else if (x == 0 && y < 0) theta = 3 / 2 * Math.PI;

            return new Spherical((float)rho, (float)theta, (float)phi);
        }
    }
}
